/**   
 *    
 * 项目名称：SmartKungFuService   
 * 类名称：OrderAddServlet   
 * 类描述：创建订单接口
 * 创建人：zhangl  
 * 创建时间：2016年9月27日 下午4:30:45   
 * 修改人：zhangl   
 * 修改时间：2016年9月27日 下午4:30:45   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.servlet;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.common.IdWorker;
import com.lst.entity.request.OrderReqPara;
import com.lst.entity.response.OrderResPara;
import com.lst.model.ClientCourse;
import com.lst.model.ClientGrowthUsed;
import com.lst.model.ClientRoll;
import com.lst.model.GymnasiumDetail;
import com.lst.model.MstOrder;
import com.lst.model.MstRoll;
import com.lst.model.OrderDetail;
import com.lst.model.ProjectDetail;
import com.lst.model.ProjectInfo;
import com.lst.service.ClientCourseService;
import com.lst.service.ClientGrowthUsedService;
import com.lst.service.ClientRollService;
import com.lst.service.GymnasiumDetailService;
import com.lst.service.MstOrderService;
import com.lst.service.MstRollService;
import com.lst.service.OrderDetailService;
import com.lst.service.ProjectDetailService;
import com.lst.service.ProjectInfoService;
import com.lst.utils.CommonUtils;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

/**
 * @ClassName: OrderAddServlet
 * @Description: 创建订单接口
 * @author zhangl
 * @date 2016年9月27日 下午4:30:45
 * 
 */
public class OrderAddServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private MstOrderService mstOrderService = ctx
			.getBean(MstOrderService.class);

	private OrderDetailService orderDetailService = ctx
			.getBean(OrderDetailService.class);

	private ProjectDetailService projectDetailService = ctx
			.getBean(ProjectDetailService.class);

	private ClientCourseService clientCourseService = ctx
			.getBean(ClientCourseService.class);

//	private ClientRollService clientRollService = ctx.getBean(ClientRollService.class);
//
//	private MstRollService mstRollService = ctx.getBean(MstRollService.class);
//
//	private ClientGrowthUsedService clientGrowthService = ctx.getBean(ClientGrowthUsedService.class);

	private ProjectInfoService projectInfoService = ctx.getBean(ProjectInfoService.class); 

	private GymnasiumDetailService gymnasiumDetailService = ctx.getBean(GymnasiumDetailService.class);	

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	synchronized public void doPost(HttpServletRequest request,
			HttpServletResponse response) {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);

		OrderResPara resPara = new OrderResPara();

		try {
			OrderReqPara reqPara = getReqPara(request);

			if (isCheckField(reqPara, resPara)) {
				Integer clientid = Integer.valueOf(reqPara.getUserid());
				Integer actid = Integer.valueOf(reqPara.getActid());
				Integer acttype = Integer.valueOf(reqPara.getActtype());
				String actname =reqPara.getActname();
				String actbill = reqPara.getActbill();
//				String packageid = reqPara.getPackageid();
//				String pachpagetypename = reqPara.getPackpagetypename();
				String scheid = reqPara.getScheid();
				Integer num = Integer.valueOf(reqPara.getNum());
				BigDecimal preprice = new BigDecimal(reqPara.getPreprice());
				String actprice = reqPara.getActprice();
				String contact = reqPara.getContact();
				String phoneno = reqPara.getPhoneno();
				String paytype = reqPara.getPaytype();
				BigDecimal price = new BigDecimal(reqPara.getPrice());
//				String ticket = reqPara.getTicket();
//				String ticprice = reqPara.getTicprice();
//				String grade = reqPara.getGrade();
//				String graprice = reqPara.getGraprice();		

				// 订单
				MstOrder mstOrder = new MstOrder();
				mstOrder.setActbill(actbill);
				mstOrder.setActid(actid);
				mstOrder.setActname(actname);
				mstOrder.setActprice(StringUtils.isEmpty(actprice) ? null
						: new BigDecimal(actprice));
				mstOrder.setActtype(acttype);
				mstOrder.setClientid(clientid);
				mstOrder.setContact(contact);
				mstOrder.setCreatedate(startDate);
				mstOrder.setUpdatedate(startDate);
				mstOrder.setCreateuser(clientid);
				mstOrder.setEnabled(true);
				mstOrder.setIsdeleted(false);
	//			mstOrder.setPackageid(StringUtils.isEmpty(packageid) ? null: Integer.valueOf(packageid));
				mstOrder.setPhoneno(phoneno);
				mstOrder.setPreprice(preprice);
				mstOrder.setScheid(scheid);
				mstOrder.setNum(num);
				mstOrder.setPaytype(StringUtils.isEmpty(paytype) ? null
						: Integer.valueOf(paytype));
				mstOrder.setPrice(price);
				// 唯一的交易流水号
				IdWorker worker = new IdWorker(2);
				String tradeno = String.valueOf(worker.nextId());

				mstOrder.setTradeno(tradeno);

				if(CommCode.SYSTEM_CARESEL_RANGE_PRO.equals(acttype)){
					ProjectInfo pi = projectInfoService.selectByPrimaryKey(actid);
					mstOrder.setReserved12(pi.getReserved12());
				}else{
					GymnasiumDetail gd = gymnasiumDetailService.selectByPrimaryKey(actid);
					mstOrder.setReserved12(gd.getReserved12());
				}

				mstOrderService.insert(mstOrder);

				MstOrder _mstOrder = new MstOrder();
				_mstOrder.setId(mstOrder.getId());
				_mstOrder.setOrderno("SKF"
						+ (CommCode.ORDERNO + mstOrder.getId()));
				mstOrderService.updateByPrimaryKeySelective(_mstOrder);

				mstOrder.setOrderno(_mstOrder.getOrderno());

				//格式化时间
				String ordertime = DateUtil.getFormatTime(mstOrder.getCreatedate(), DateUtil.ALL_DATETIME_ORDER);
				mstOrder.setOrdertime(ordertime);	

				if (CommCode.SYSTEM_CARESEL_RANGE_PRO.equals(acttype)) {

					ProjectDetail pd = new ProjectDetail();
					pd.setClientid(clientid);
					pd.setCreatedate(startDate);
					pd.setCreateuser(clientid);
					pd.setEnabled(true);
					pd.setIsdeleted(false);
					pd.setOrderid(mstOrder.getId());
					pd.setPayprice(StringUtils.isEmpty(actprice) ? null
							: new BigDecimal(actprice));
					pd.setProid(actid);
					pd.setProtitle(actname);

					projectDetailService.insert(pd);
				} else {
					ClientCourse cc = new ClientCourse();
					cc.setClientid(clientid);
					cc.setCourseid(actid);
					cc.setCreatedate(startDate);
					cc.setCreateuser(clientid);
					cc.setEnabled(true);
					cc.setIsdeleted(false);
					cc.setOrderid(mstOrder.getId());
//					cc.setPackpagetype(StringUtils.isEmpty(packageid) ? null: Integer.valueOf(packageid));
//					cc.setPackpagetypename(StringUtils.isEmpty(pachpagetypename) ? null : CommFun.Filter(pachpagetypename));
					cc.setStartdate(null);
					cc.setEnddate(null);

					clientCourseService.insert(cc);
				}

				OrderDetail orderDetail = new OrderDetail();

				// 订单详情
				orderDetail.setOrderid(mstOrder.getId());
				orderDetail.setClientid(clientid);
				orderDetail.setNum(num);
				orderDetail.setPreprice(preprice);
//				orderDetail.setTicket(StringUtils.isEmpty(ticket) ? null: Integer.valueOf(ticket));
//				orderDetail.setTicprice(StringUtils.isEmpty(ticprice) ? null: new BigDecimal(ticprice));
//				orderDetail.setGrade(StringUtils.isEmpty(grade) ? null: Integer.valueOf(grade));
//				orderDetail.setGraprice(StringUtils.isEmpty(graprice) ? null: new BigDecimal(graprice));
				orderDetail.setActprice(StringUtils.isEmpty(actprice) ? null
						: new BigDecimal(actprice));
				orderDetail.setOrderstatus(CommCode.SYSTEM_ORDER_STATUS_PAY);
				orderDetail.setCreatedate(startDate);
				orderDetail.setUpdatedate(startDate);
				orderDetail.setCreateuser(clientid);
				orderDetail.setEnabled(true);
				orderDetail.setIsdeleted(false);
				orderDetail.setPrice(price);

				orderDetailService.insert(orderDetail);

	//			ClientRoll cr = null;
	//			ClientGrowthUsed cgu = null;

				// 优惠券
//				if (!StringUtils.isEmpty(ticket)) {
//
//					MstRoll mr = mstRollService.selectByPrimaryKey(Integer.valueOf(ticket));
//
//					cr = new ClientRoll();
//
//					cr.setClientid(clientid);
//					cr.setRollid(Integer.valueOf(ticket));
//					cr.setAritype(mr.getAritype());
//					cr.setValue(mr.getValue());
//					cr.setContent(mr.getContent());
//					cr.setRollstatus(CommCode.ROLLSTATUS_USED);
//					cr.setCreatedate(startDate);
//					cr.setCreateuser(clientid);
//					cr.setEnabled(true);
//					cr.setIsdeleted(false);
//
//					clientRollService.insert(cr);
//
//					orderDetail.setReserved2(cr.getId());
//					orderDetail.setUpdatedate(new Date());
//					orderDetail.setUpdateuser(clientid);
//
//					orderDetailService.updateByPrimaryKeySelective(orderDetail);
//				}

				// 用户成就使用
//				if (!StringUtils.isEmpty(grade)) {
//
//					cgu = new ClientGrowthUsed();
//
//					cgu.setClientid(clientid);
//					cgu.setGraid(Integer.valueOf(grade));
//					cgu.setOrderid(mstOrder.getId());
//					cgu.setGrowthvalue(Integer.valueOf(CommonUtils
//							.getGrowth_value_order()));
//					cgu.setGraprice(orderDetail.getGraprice());
//					cgu.setCreatedate(startDate);
//					cgu.setCreateuser(clientid);
//					cgu.setEnabled(true);
//					cgu.setIsdeleted(false);
//
//					clientGrowthService.insert(cgu);
//
//					orderDetail.setReserved1(cgu.getId());
//					orderDetail.setUpdatedate(new Date());
//					orderDetail.setUpdateuser(clientid);
//
//					orderDetailService.updateByPrimaryKeySelective(orderDetail);
//				}

				OrderDetail orderdetail = orderDetailService.selectByPrimaryKey(orderDetail.getId());

				resPara.setOrder(mstOrder);
				resPara.setOderdetail(orderdetail);
				resPara.setCode(CommCode.M_Y000000);
				resPara.setMessage(CommCode.M_Y000001);

				logger.info("doPost end run(s): "
						+ DateUtil.calLastedTime(startDate));
			}

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}

		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
					.excludeFieldsWithoutExposeAnnotation().serializeNulls()
					.create();
			String jsonResult = gson.toJson(resPara);
			logger.info(jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

			logger.info("doPost end run(s): "
					+ DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public OrderReqPara getReqPara(HttpServletRequest request) {

		OrderReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request,
					new OrderReqPara());

			reqPara = (OrderReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");// 用户ID
			String actid = request.getParameter("actid");// 活动或课程ID
			String acttype = request.getParameter("acttype");// 活动：11，课程：298
			String actname = request.getParameter("actname");// 对应名称
			String actbill = request.getParameter("actbill");// 图片路径
//			String packageid = request.getParameter("packageid");// 套餐
//			String packpagetypename = request.getParameter("packpagetypename");// 套餐名
			String scheid = request.getParameter("scheid");// 选取时间
			String num = request.getParameter("num");// 数量
			String preprice = request.getParameter("preprice");// 原价
			String actprice = request.getParameter("actprice");// 现价
			String contact = request.getParameter("contact");// 联系人
			String phoneno = request.getParameter("phoneno");// 联系电话
			String paytype = request.getParameter("paytype");// 支付方式
			String price = request.getParameter("price");// 单价
//			String ticket = request.getParameter("ticket");// 优惠券
//			String ticprice = request.getParameter("ticprice");// 优惠券价格
//			String grade = request.getParameter("grade");// 等级
//			String graprice = request.getParameter("graprice");// 等级优惠

			logger.info("reqPara userid: " + userid);
			logger.info("reqPara actid: " + actid);
			logger.info("reqPara acttype: " + acttype);
			logger.info("reqPara actname: " + actname);
			logger.info("reqPara actbill: " + actbill);
//			logger.info("reqPara packageid: " + packageid);
//			logger.info("reqPara packpagetypename: " + packpagetypename);
			logger.info("reqPara scheid: " + scheid);
			logger.info("reqPara num: " + num);
			logger.info("reqPara preprice: " + preprice);
			logger.info("reqPara actprice: " + actprice);
			logger.info("reqPara contact: " + contact);
			logger.info("reqPara phoneno: " + phoneno);
			logger.info("reqPara paytype: " + paytype);
			logger.info("reqPara price: " + price);
//			logger.info("reqPara ticket: " + ticket);
//			logger.info("reqPara ticprice: " + ticprice);
//			logger.info("reqPara grade: " + grade);
//			logger.info("reqPara graprice: " + graprice);

			reqPara.setUserid(userid);
			reqPara.setActid(actid);
			reqPara.setActtype(acttype);
			reqPara.setActname(actname);
			reqPara.setActbill(actbill);
//			reqPara.setPackageid(packageid);
//			reqPara.setPackpagetypename(packpagetypename);
			reqPara.setScheid(scheid);
			reqPara.setNum(num);
			reqPara.setPreprice(preprice);
			reqPara.setActprice(actprice);
			reqPara.setContact(contact);
			reqPara.setPhoneno(phoneno);
			reqPara.setPaytype(paytype);
			reqPara.setPrice(price);
			reqPara.setPaytype(paytype);
//			reqPara.setTicket(ticket);
//			reqPara.setTicprice(ticprice);
//			reqPara.setGrade(grade);
//			reqPara.setGraprice(graprice);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		OrderReqPara orderReqPara = (OrderReqPara) reqPara;
		OrderResPara orderResPara = (OrderResPara) resPara;

		if (StringUtils.isEmpty(orderReqPara.getUserid())) {
			orderResPara.setCode(CommCode.M_A000000);
			orderResPara.setMessage(CommCode.M_P000002);
		} else if (StringUtils.isEmpty(orderReqPara.getActid())) {
			orderResPara.setCode(CommCode.M_A000000);
			orderResPara.setMessage(CommCode.M_E000002);
		} else if (StringUtils.isEmpty(orderReqPara.getActtype())) {
			orderResPara.setCode(CommCode.M_A000000);
			orderResPara.setMessage(CommCode.M_E000003);
		} else if (StringUtils.isEmpty(orderReqPara.getActname())) {
			orderResPara.setCode(CommCode.M_A000000);
			orderResPara.setMessage(CommCode.M_E000004);
		} else if (StringUtils.isEmpty(orderReqPara.getActbill())) {
			orderResPara.setCode(CommCode.M_A000000);
			orderResPara.setMessage(CommCode.M_E000005);
		} else if (StringUtils.isEmpty(orderReqPara.getNum())) {
			orderResPara.setCode(CommCode.M_A000000);
			orderResPara.setMessage(CommCode.M_E000028);
		} else if (StringUtils.isEmpty(orderReqPara.getPreprice())) {
			orderResPara.setCode(CommCode.M_A000000);
			orderResPara.setMessage(CommCode.M_E000026);
		} else if (StringUtils.isEmpty(orderReqPara.getActprice())) {
			orderResPara.setCode(CommCode.M_A000000);
			orderResPara.setMessage(CommCode.M_E000006);
		} else if (StringUtils.isEmpty(orderReqPara.getContact())) {
			orderResPara.setCode(CommCode.M_A000000);
			orderResPara.setMessage(CommCode.M_E000007);
		} else if (StringUtils.isEmpty(orderReqPara.getPhoneno())) {
			orderResPara.setCode(CommCode.M_A000000);
			orderResPara.setMessage(CommCode.M_E000008);
		} else if (StringUtils.isEmpty(orderReqPara.getPaytype())) {
			orderResPara.setCode(CommCode.M_A000000);
			orderResPara.setMessage(CommCode.M_E000011);
		} else if (StringUtils.isEmpty(orderReqPara.getPrice())) {
			orderResPara.setCode(CommCode.M_A000000);
			orderResPara.setMessage(CommCode.M_E000027);
		} else {
			flag = true;
		}
		return flag;
	}

}
